package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

public class Configuration {
    private static final Logger LOG = LoggerFactory.getLogger(Configuration.class);
    private static final String propertyPath = "/configuration.properties";

    private static final Properties properties = new Properties();
    static {
        InputStream in = Object.class.getResourceAsStream(propertyPath);
        try {
            properties.load(in);
        } catch (IOException e) {
            LOG.info("Error occurs when reading configuration file, use DEFAULT configuration");
        }
    }

    public static String endpoint;
    static {
        if (!properties.containsKey("endpoint")) {
            endpoint = UUID.randomUUID().toString();
            updateKey("endpoint", endpoint);
        } else {
            endpoint = properties.getProperty("endpoint");
        }
    }
    public static String sensorType = properties.getProperty("sensorType", "undefined type");
    public static int defaultIntervalPeriod = Integer.parseInt(
            properties.getProperty("defaultIntervalPeriod", "30"));
    public static double waterCount = Double.valueOf(
            properties.getProperty("waterCount", "0"));
    public static String sensorUnit = properties.getProperty("sensorUnit", "Unknown");
    public static String applicationType = properties.getProperty("applicationType", "Unset");
    public static String model = properties.getProperty("model");

    public static void updateKey(String key, String value) {
        properties.setProperty(key, value);
        FileOutputStream stream = null;
        try {
//            stream = new FileOutputStream(ClassLoader.getSystemResource("configuration.properties").getPath());
            stream = new FileOutputStream("configuration.properties");
            properties.store(stream, "");
        } catch (IOException e) {
            LOG.warn("Property file missing, fail to write key[{}]", key);
        } finally {
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
